#pragma once
#include <iostream>
#include "Protocol.hpp"

using namespace std;

enum
{
    Div_Zero = 1,
    Mod_Zero,
    Other_Oper
};


class ServerCal
{
private:
    // 计算器的核心算法
    Response CalculateHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
        case '+':
            resp.result = req.x + req.y;
            break;
       
        case '-':
            resp.result = req.x - req.y;
            break;
       
        case '*':
            resp.result = req.x * req.y;
            break;
       
        case '/':
        {
            if (req.y == 0)
                resp.code = Div_Zero;
            else
                resp.result = req.x / req.y;
        }
        break;      //break可以放在{}外面，表示一个代码块的结束
        
        case '%':
        {
            if (req.y == 0)
                resp.code = Mod_Zero;
            else
                resp.result = req.x % req.y;
        }
        break;
        
        default:
            resp.code = Other_Oper;
            break;
        }

        return resp;
    }


public:
    // "len"\n"10 + 20"\n
    std::string Calculator(std::string &package)
    {
        string content;
        
        bool r = Decode(package, &content);
        if (!r) return "Decode Error";

        //"10 + 20"
        Request req;
        r = req.Deserialize(content);   //"10 + 20" ->x=10 op=+ y=20,存放在了req中
        content.clear();

        Response rsp;
        rsp = CalculateHelper(req);     // result=30 code=0;

        r = rsp.Serialize(&content);     // "30 0"
        if (!r) return "Serialize Error";

        Encode(content);     // "len"\n"30 0"

        return content;
    }

};